package com.net.wanjian.networkhospitalmanager.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.joooonho.SelectableRoundedImageView;
import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.skilltrain.LaboratoryListActivity;
import com.net.wanjian.networkhospitalmanager.activity.skilltrain.SkillTrainActivity;
import com.net.wanjian.networkhospitalmanager.adapter.base.RecyclerBaseAdapter;
import com.net.wanjian.networkhospitalmanager.bean.EnterLabResult;
import com.net.wanjian.networkhospitalmanager.bean.StudentApplyReserveReturn;
import com.net.wanjian.networkhospitalmanager.bean.StudentLabReserveListResult;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.consts.LabReserveBtnConst;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.TimeDateUtils;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.observers.DisposableObserver;

/**
 * Description: 学生实验预约列表
 * Created by lidongcai on 17/4/27.
 * Email:  lidongcaiocc@163.com
 */

public class MyReserveListAdapter extends RecyclerBaseAdapter<StudentLabReserveListResult.DataBean.CurrentLabReserveListBean, MyReserveListAdapter.ViewHolder> {
    //    private SkillTrainActivity activity;
    private LocalBroadcastManager localBroadcastManager;

    public MyReserveListAdapter(Context context) {
        super(context);
//        this.activity = (SkillTrainActivity) context;
        localBroadcastManager = LocalBroadcastManager.getInstance(context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_my_reserve_list, parent, false);
        AutoUtils.auto(view);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final StudentLabReserveListResult.DataBean.CurrentLabReserveListBean d, final int position) {
        //设置实验名称
        holder.setLabNameTv(URLDecoderUtil.getDecoder(d.getLabReserveName()));

        //是否存在指导教师（0不存在，1存在）
        if (URLDecoderUtil.getDecoder(d.getIsExistGuideTeacher()).equals("0")) {
            holder.setLabIsGuideTeacherIv(false);
        } else {
            holder.setLabIsGuideTeacherIv(true);
        }
        //技能名称集合（中间以英文逗号隔开）
        holder.setLabSkillTv("练习技能：" + URLDecoderUtil.getDecoder(d.getTrainTypeNameArray()));

        //设置开放到关闭的时间，需要格式化
        String openTime = TimeDateUtils.formatTimeFriend(URLDecoderUtil.getDecoder(d.getLabReserveOpenTime()));
        String closeTime = TimeDateUtils.formatTimeFriend(URLDecoderUtil.getDecoder(d.getLabReserveCloseTime()));
        String ot = openTime.split(" ")[0];
        String ct = closeTime.split(" ")[0];
        if (ot.equals(ct)) {
            holder.setLabStartTimeTv(openTime + "—" + closeTime.split(" ")[1]);
        } else {
            holder.setLabStartTimeTv(openTime + "—" + closeTime);
        }

        //学生预约按钮的状态
        //服务器已经取消
        if (d.getLabReserveStatus().equals("2")) {
            holder.setLabReserveBtn(LabReserveBtnConst.SERVER_CANCEL);
        } else {
            //未到截止时间，取消预约
            if (TimeDateUtils.isStopTime(URLDecoderUtil.getDecoder(d.getLabReserveEndTime()))) {

                //过了截止时间，判断是否开放那天（这里只要过了0点，就可以进入实验室）
                if (TimeDateUtils.isOpenTime(URLDecoderUtil.getDecoder(d.getLabReserveOpenTime()))) {
                    holder.setLabReserveBtn(LabReserveBtnConst.ENTER_LAB);
                } else {
                    holder.setLabReserveBtn(LabReserveBtnConst.WAIT_OPEN);
                }
            } else {
                holder.setLabReserveBtn(LabReserveBtnConst.CANCEL_RESERVED);
            }

        }

        holder.labReserveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入实验室
                if (TimeDateUtils.isStopTime(URLDecoderUtil.getDecoder(d.getLabReserveEndTime()))) {
                    enterLabHttpRequest(d.getLabReserveID(), d.getLabReserveName());
                } else {
                    //取消预约
                    HttpUtil.studentCancelReserve(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                            SharedXmlUtil.getInstance().getHospitalId(), SharedXmlUtil.getInstance().getUserIdentityId(), d.getLabReserveID(), new DisposableObserver<StudentApplyReserveReturn>() {
                                @Override
                                public void onNext(StudentApplyReserveReturn studentApplyReserveReturn) {
                                    if (studentApplyReserveReturn.getResult().equals("1")) {
                                        ToastUtil.showToast("成功取消预约");
                                        list.remove(position);
                                        notifyDataSetChanged();
                                        //通知刷新学生预约列表
//                                        activity.refreshLabReserveList();
                                        localBroadcastManager.sendBroadcast(new Intent("refreshlabreserve"));

                                    } else {
                                        ToastUtil.showToast("无法取消预约");
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onComplete() {

                                }
                            });

                }

//                activity.refreshLabReserveList();
            }
        });
    }


    /**
     * 进入实验室权限验证
     *
     * @param labReserveId
     */
    private void enterLabHttpRequest(final String labReserveId, final String labName) {
        HttpUtil.enterLab(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                SharedXmlUtil.getInstance().getHospitalId(), SharedXmlUtil.getInstance().getUserIdentityId(), labReserveId, new DisposableObserver<EnterLabResult>() {
                    @Override
                    public void onNext(EnterLabResult enterLabResult) {
                        if (enterLabResult.getResult().equals(ErrorCodeReturn.success + "")) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(enterLabResult.getData().getToken()));

                            Bundle bundle = new Bundle();
                            bundle.putString(LaboratoryListActivity.LAB_RESERVE_MEMBER_ID_KEY, URLDecoderUtil.getDecoder(enterLabResult.getData().getLabReserveMember().getLabReserveMemberID()));
                            bundle.putString(LaboratoryListActivity.LAB_RESERVE_NAME_KEY, URLDecoderUtil.getDecoder(labName));
                            bundle.putString(LaboratoryListActivity.LAB_RESERVE_ID_KEY, URLDecoderUtil.getDecoder(labReserveId));
                            Intent intent = new Intent(context, LaboratoryListActivity.class);
                            intent.putExtras(bundle);
                            context.startActivity(intent);
                        } else {
                            ToastUtil.showToast("请签到后进入实验室");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.lab_name_tv)
        TextView labNameTv;
        @BindView(R.id.lab_skill_tv)
        TextView labSkillTv;
        @BindView(R.id.lab_start_time_tv)
        TextView labStartTimeTv;
        @BindView(R.id.lab_is_guide_teacher_iv)
        SelectableRoundedImageView labIsGuideTeacherIv;
        @BindView(R.id.relativeLayout)
        RelativeLayout relativeLayout;
        @BindView(R.id.lab_reserve_btn)
        Button labReserveBtn;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }


        public void setLabNameTv(String labNameTv) {
            this.labNameTv.setText(labNameTv);
        }

        public void setLabSkillTv(String labSkillTv) {
            this.labSkillTv.setText(labSkillTv);
        }

        public void setLabStartTimeTv(String labStartTimeTv) {
            this.labStartTimeTv.setText(labStartTimeTv);
        }

        public void setLabIsGuideTeacherIv(boolean b) {
            if (b) {
                labIsGuideTeacherIv.setBackgroundResource(R.mipmap.practice_btn_green);
            } else {
                labIsGuideTeacherIv.setBackgroundResource(R.mipmap.practice_btn_grey);
            }
        }


        public void setLabReserveBtn(int type) {
            switch (type) {
                case LabReserveBtnConst.NO_RESERVED:
                    labReserveBtn.setVisibility(View.GONE);
                    break;
                case LabReserveBtnConst.UNABLE_RESERVED:
                    labReserveBtn.setEnabled(false);
                    labReserveBtn.setText("立即预约");
                    labReserveBtn.setBackgroundResource(R.drawable.lab_reserve_btn_color);
                    break;
                case LabReserveBtnConst.CAN_RESERVED:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("立即预约");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
                case LabReserveBtnConst.CANCEL_RESERVED:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("取消预约");
                    labReserveBtn.setBackgroundResource(R.drawable.btn_bg_cancel);
                    break;
                case LabReserveBtnConst.WAIT_OPEN:
                    labReserveBtn.setEnabled(false);
                    labReserveBtn.setText("等待开放");
                    labReserveBtn.setBackgroundResource(R.drawable.lab_reserve_btn_color);
                    break;
                case LabReserveBtnConst.ENTER_LAB:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("进入实验室");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
                case LabReserveBtnConst.SERVER_CANCEL:
                    labReserveBtn.setEnabled(false);
                    labReserveBtn.setText("服务器已取消");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
                case LabReserveBtnConst.RECEIPT:
                    labReserveBtn.setEnabled(true);
                    labReserveBtn.setText("回执");
                    labReserveBtn.setBackgroundResource(R.drawable.my_reserve_btn_color);
                    break;
            }
        }
    }
}
